package com.zf.admin.controller;

import com.zf.admin.comment.Result;
import com.zf.admin.pojo.User;
import com.zf.admin.service.UserService;
import com.zf.admin.utils.CookieUtils;
import com.zf.admin.utils.MD5Utils;
import com.zf.admin.utils.image.ImageCode;
import com.zf.admin.utils.jwt.JwtService;
import com.zf.admin.utils.mail.IMailService;
import com.zf.admin.utils.verificationcode.VerificationCodeUtils;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private IMailService mailService;

    /**
     * 描述: 登录
     *
     * @param user
     * @param model
     * @param session
     * @param response
     * @param code
     * @return java.lang.String
     * @author LJH-1755497577 2019/9/12 20:13
     */
    @RequestMapping("/logincheck")
    public String login(User user, Model model,
                        HttpSession session,
                        HttpServletResponse response,
                        String code) throws Exception {

        //判断验证码
        if (!session.getAttribute("code").toString().toLowerCase()
                .equals(code.toLowerCase())) {
            String error = "codeerror";
            model.addAttribute("error", error);
            return "login";
        }

        //验证用户
        User user1 = userService.login(user);

        if (user1 != null) {

            if (user1.getType().equals("admin")
                    && MD5Utils.getMd5Hash(user.getPassword(), user.getUsername()).toString().equals(user1.getPassword())) {
                Map<String, String> map = new HashMap<>();
                map.put("name", user1.getUsername());
                CookieUtils.setCookie(response, "authorization", JwtService.createPersonToken(map, "codeAnt"));
                CookieUtils.setCookie(response, "name", user1.getUsername());
//                return "admin/main1";
                return "admin/main1";
            }
            String error = "error";
            model.addAttribute("error", error);
            return "login";
        } else {
            String error = "error";
            model.addAttribute("error", error);
            return "login";
        }
    }

    /**
     * 描述: 注销账户，消除cookie
     *
     * @param response
     * @param request
     * @return java.lang.String
     * @author LJH-1755497577 2019/9/13 0:22
     */
    @RequestMapping("/logout")
    public String logout(HttpServletResponse response, HttpServletRequest request) throws Exception {

        for (Cookie c : request.getCookies()) {
            CookieUtils.removeCookie(response, c);
        }
        return "login";
    }


    /**
     * 描述: 图形验证码（登录需要）
     *
     * @param res
     * @param resp
     * @return void
     * @author gp
     */
    @GetMapping("imagecode")
    public void image(HttpServletRequest res,
                      HttpServletResponse resp,
                      HttpSession session) throws Exception {
        ImageCode imageCode = new ImageCode();
        String random = imageCode.createImage(resp, res);
        if (session.getAttribute("code") == null) {
            session.setAttribute("code", random);
            return;
        }
        session.setAttribute("code", random);
    }

    /**
     * 描述: 注册
     *
     * @param user
     * @return java.lang.String
     * @author LJH-1755497577 2019/9/13 0:39
     */
    @PostMapping(value = "registercheck",produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result register(User user, String code) {
        //判断用户
        if (StringUtil.isNullOrEmpty(user.getUsername())
                || StringUtil.isNullOrEmpty(user.getPassword())) {
        return Result.getInstance(0,"用户名或密码为空");
        }

        if (userService.isExist(user.getUsername())) {
            return Result.getInstance(0,"用户名已使用");
        }

        //验证验证码
        Result temp = Verify(user.getUsername(), code);
        if (temp != null) {
            return temp;
        }

        //修改属性
        user.setType("admin");
        //加密密码
        user.setPassword(MD5Utils.getMd5Hash(user.getPassword(), user.getUsername()).toString());

        userService.register(user);
        return Result.getInstance(1, "注册成功");
    }

    /**
     * 描述: 发送邮件验证码
     *
     * @param to       发给谁邮箱
     * @param userName 用户Id
     * @return com.cqut.minishop.comment.Result
     * @author LJH-1755497577 2019/8/24 21:46
     */
    @PostMapping(value = "sendMail",produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result sendMail(@RequestParam(name = "to", required = false) String to,
                           @RequestParam(name = "username", required = false) String userName) {

        //判断用户
        if (StringUtil.isNullOrEmpty(userName)
                || StringUtil.isNullOrEmpty(to)) {
            return Result.getInstance(0, "用户名/或邮箱为空");

        }
        if(!to.matches("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?")){
            return Result.getInstance(0, "请输入正确的邮箱！");
        }

        //验证用户
        if (userService.isExist(userName)) {
            return Result.getInstance(0, "用户名已使用");
        }

        mailService.sendSimpleMail(to, "租房客-注册验证码", "验证码：" + VerificationCodeUtils.getCode(userName) + "(三分钟内有效)");

        return Result.getInstance(1, "发送成功");
    }


    /**
     * 描述: 验证验证码
     *
     * @param code
     * @return com.cqut.minishop.comment.Result
     * @author LJH-1755497577 2019/8/29 18:12
     */
    private Result Verify(String username, String code) {
        if (StringUtils.isEmpty(code)) {
            return Result.getInstance(0, "请输入验证码");
        }

        if (!VerificationCodeUtils.verifyTime(username)) {
            return Result.getInstance(0, "验证码过期");
        }

        if (!VerificationCodeUtils.verify(username, code)) {
            return Result.getInstance(0, "验证码错误");
        }
        return null;
    }

}

